﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DryIoc;
using HandyControl.Controls;
using HandyControl.Tools;
using Ku.AppCore;
using Ku.Common;
using Ku.Start.Model;
using Ku.Start.Views;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml.Linq;

namespace Ku.Start.ViewModels
{
    public partial class MainWindowViewModel : ViewModelBase, IConfigureService
    {
        private readonly IRegionManager _regionManager;
        private readonly IContainerProvider _containerProvider;

        [ObservableProperty]
        private string _title = "Ku工具";

        [ObservableProperty]
        private string _Version = "软件版本";


        public MainWindowViewModel(IRegionManager regionManager, IContainerProvider containerProvider)
        {
            _regionManager = regionManager;
            _containerProvider = containerProvider;

            //软件版本
            var version = Assembly.GetExecutingAssembly().GetName().Version;
            Version = $"v{version}";
            SetMenu();

        }

        #region 菜单
        /// <summary>
        /// 菜单
        /// </summary>
        [ObservableProperty]
        private List<MenuModel> _MenuList = new List<MenuModel>();
        /// <summary>
        /// 菜单选中项
        /// </summary> 
        private MenuModel _MenuSelectedItem;

        public MenuModel MenuSelectedItem
        {
            get => _MenuSelectedItem;
            set
            {
                //doFloorNumberChanged();//自定义事件
                SetProperty(ref _MenuSelectedItem, value);
            }
        }
        private void SetMenu()
        {
            MenuList = new List<MenuModel>();
            //MenuList.Add(new MenuModel() { Name = "首页", ImageBrush = ResourceHelper.GetResource<object>("FatalGeometry"), TargetCtlName = "Home" });
            //MenuList.Add(new MenuModel() { Name = "MainTabItem", ImageBrush = ResourceHelper.GetResource<object>("CalendarGeometry"), TargetCtlName = "MainTabItem" });
            //MenuList.Add(new MenuModel() { Name = "菜单B", ImageBrush = ResourceHelper.GetResource<object>("CalendarGeometry"), TargetCtlName = "MainTabItemB" });

            string path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "Data", "Menu.json");
            var menuJson = FileHelper.ReadFile(path);
            var tempList = menuJson.DeserializeObject<List<MenuModel>>();
            foreach (var item in tempList)
            {
                if (item.IsVisible)
                {
                    MenuList.Add(new MenuModel()
                    {
                        Name = item.Name,
                        ImageBrush = ResourceHelper.GetResource<object>(item.ImageBrush.ToString()),
                        TargetCtlName = item.TargetCtlName,
                        QueriesText = item.QueriesText,
                    });
                }
            }
            MenuSelectedItem = MenuList[0];

        }

        #endregion

        #region 事件

        [RelayCommand]
        private void Navigate(object parameter)
        {
            MenuModel selectedItem = parameter as MenuModel;

            // 导航时传递参数
            var parameters = new NavigationParameters();
            parameters.Add("HeaderName", selectedItem.Name);
            parameters.Add("ViewName", selectedItem.TargetCtlName);
            parameters.Add("IconBrush", selectedItem.ImageBrush);
            _regionManager.RequestNavigate(RegionNames.MainTabRegion, selectedItem.TargetCtlName, result =>
            {
                if (!result.Success)
                {
                    // Handle error
                    Debug.WriteLine(result.Exception);
                }
                else
                { 
                    //var regions = _regionManager.Regions[RegionNames.MainTabRegion];
                    //if (regions != null && regions.Views.Contains(selectedItem.TargetCtlName))
                    //{
                    //    //regions.Remove(view);
                    //}
                    //var view = regions.GetView(selectedItem.TargetCtlName);
                    //if (view != null)
                    //    regions.Activate(view);

                    //Debug.WriteLine("导航成功");
                }
            }, parameters);
            GetRegions();

        }

        public void GetRegions()
        {

            foreach (var region in _regionManager.Regions)
            {
                List<string> viewNameList = new List<string>();
                System.Text.StringBuilder sbView = new System.Text.StringBuilder();
                foreach (var view in region.Views)
                {
                    var type = view.GetType();
                    var name = type.Name;
                    var fullName = type.FullName;
                    viewNameList.Add(name);

                    sbView.Append($"{name}，");

                    //var viewModel = view.DataContext as ViewModelBase;
                    //var viewName = viewModel.ViewName;

                    //Debug.WriteLine($"视图： {name}");
                }

                Debug.WriteLine($"【{DateTime.Now.ToString("MM:dd HH:mm:ss")}】区域名称： {region.Name}---> 视图（{viewNameList.Count}）： {sbView.ToString()}");
            }
        }



        [RelayCommand]
        private void ClosingCmd(object parameter)
        {
            try
            {
                var args = parameter as RoutedEventArgs;
                if (args != null)
                {
                    var closingTabItem = args.OriginalSource;
                    if (closingTabItem != null)
                    {
                        var regions = _regionManager.Regions[RegionNames.MainTabRegion];
                        if (regions.Views.Contains(closingTabItem))
                        {
                            regions.Remove(closingTabItem);
                        };
                    }
                }

            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// tab切换事件
        /// </summary>
        /// <param name="parameter"></param>
        [RelayCommand]
        private void SwitchMenu(object parameter)
        {
            var args = parameter as SelectionChangedEventArgs;
            if (args != null && args.AddedItems.Count > 0)
            {
                var selectedTab = args.AddedItems[0] as HandyControl.Controls.TabItem;
                var closingTabItem = args.OriginalSource;
                if (selectedTab != null)
                {
                    var region = _regionManager.Regions[RegionNames.MainTabRegion];
                    var activeView = region.ActiveViews.FirstOrDefault() as FrameworkElement;
                    var viewModel = activeView.DataContext as ViewModelBase;
                    var viewName = viewModel.ViewName;
                    Debug.WriteLine($"【{DateTime.Now.ToString("MM:dd HH:mm:ss")}】切换菜单-->{viewName}");
                    //SetMenuSelectedItem(viewName);
                }
            }
        }
        /// <summary>
        /// 设置 选中菜单
        /// </summary>
        private void SetMenuSelectedItem(string viewName)
        {
            var entity = _MenuList.Find(w => w.TargetCtlName == viewName);
            if (entity != null)
            {
                if (entity.TargetCtlName != MenuSelectedItem.TargetCtlName)
                {
                    MenuSelectedItem = entity;
                }
            }
        }
        public void Configure()
        {
            //设置默认选中的
            _regionManager.RequestNavigate(RegionNames.MainTabRegion, MenuList[0].TargetCtlName);
        }
        #endregion
    }
}
